package com.topisv.tms.web.stock.check;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.stock.check.CheckCountTask;
import com.topisv.tms.entity.stock.check.CheckPlanItem;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.check.CheckCountTaskService;
import com.topisv.tms.service.stock.check.CheckPlanItemService;

/**
 * 盘点点数任务_control
 * @author ch
 */
@Controller
@RequestMapping({"/checkCountTask"})
public class CheckCountTaskController
{

  private static final Logger logger = LoggerFactory.getLogger(CheckCountTaskController.class);
  
  @Autowired
  private CustomersService customersService;
  @Autowired
  private CheckCountTaskService checkCountTaskService;
  @Autowired
  private CheckPlanItemService checkPlanItemService;
  @Autowired
  private AreaGroupService areaGroupService;

  /**
   * 导向盘点点数任务列表页面
   * @param pageNumber
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "v2_toCheckCountTaskList")
  public String toCheckCountTaskList(@RequestParam(value="page", defaultValue="1") int pageNumber, Model model, ServletRequest request)
  {
	    try{
	    	//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//查找我的点数任务
		    Map<String, Object> params_my =new HashMap<String, Object>();
		    params_my.put("status","myTask"); //任务状态 （undo.创建点数任务 token:领取任务 doing:点数中 finish.点数完成）
		    params_my.put("workerUuid",curUser.jobuuid);
			List<CheckCountTask> myTaskList = this.checkCountTaskService.loadTask(params_my);
			model.addAttribute("myTaskList",myTaskList);
			
			//如果是派友用户，初始化数据
			if("paiu".equals(curUser.userType)){
			    //未分配的任务
			    Map<String, Object> param_untaked=new HashMap<String, Object>();
			    param_untaked.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
			    param_untaked.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param_untaked.put("status", "undo");
			    List<CheckCountTask> untakedTaskList = this.checkCountTaskService.loadTask(param_untaked);
			    model.addAttribute("untakedTaskList",untakedTaskList);
			}
			
			//如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=curUser.customerCode;
				model.addAttribute("customerCode", customerCode); 
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//未分配的任务
			    Map<String, Object> param_untaked=new HashMap<String, Object>();
			    param_untaked.put("customerCodes", customerCode);
			    param_untaked.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param_untaked.put("status", "undo");
			    List<CheckCountTask> untakedTaskList = this.checkCountTaskService.loadTask(param_untaked);
			    model.addAttribute("untakedTaskList",untakedTaskList);
			}
	    }
	    catch (Exception e) {
	      
	      logger.error(e.getMessage(),e);
	    }
	
	    return "stock/check/countTaskList";
  }
  
  
  /**
	 * 查询任务列表
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "v2_queryTaskList")
	public String queryTaskList(Model model, ServletRequest request, ServletResponse response) throws Exception {
		try {
		
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//查找我的点数任务
		    Map<String, Object> params_my =new HashMap<String, Object>();
		    params_my.put("status","myTask"); //任务状态 （undo.创建点数任务 token:领取任务 doing:点数中 finish.点数完成）
		    params_my.put("workerUuid",curUser.jobuuid);
			List<CheckCountTask> myTaskList = this.checkCountTaskService.loadTask(params_my);
			model.addAttribute("myTaskList",myTaskList);
			
		    //查询未分配的任务
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String) param.get("warehouseCode");
			String customerCode=(String) param.get("customerCode");
			
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			param.put("status", "undo");
			
			List<CheckCountTask> untakedTaskList = this.checkCountTaskService.loadTask(param);
			model.addAttribute("untakedTaskList", untakedTaskList);
			model.addAttribute("warehouseCode", warehouseCode);
			model.addAttribute("customerCode", customerCode);
			
			//初始化仓库数据
			if(StringUtils.isNotBlank(customerCode)){
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
		
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
		}

		return "stock/check/countTaskList";
	}
  
  
    /**
	 * 领取任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxTakeTask")
	public void ajaxTakeTask(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {	
			
			json = new JSONObject();
			out = response.getWriter();
			
			Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			String msg=this.checkCountTaskService.takeTask(taskId,curUser.jobuuid);

			json.put("msg", msg);
			
		} catch (Exception e) {
			
			json.put("msg","error");
			logger.error("error",e);
		}
		
		out.print(json.toString());
	}
	
	
	/**
	 * 导向点数任务页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toCountTaskPage/{taskId}", method = RequestMethod.GET)
	public String toCountTaskPage(@PathVariable("taskId") Long taskId, Model model) {
		try {

			//查询任务
		    CheckCountTask  task=this.checkCountTaskService.loadById(taskId);
		    model.addAttribute("task", task);
		    
		    //查询任务明细
		    List<CheckPlanItem> itemList=this.checkPlanItemService.loadByPlanCode(task.getPlanCode());
		    model.addAttribute("itemList", itemList);
		    
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/check/countTask";
	}
	
	//保存点数数据
	@RequestMapping(value = "ajaxSaveCountData")
	@ResponseBody
	public String ajaxSaveCountData(ServletRequest request,HttpServletResponse response) {
		try {	
			
			String jsonText=request.getParameter("jsonText");
			String taskCode=request.getParameter("taskCode");
			JSONArray jsonArray = JSONArray.fromObject(jsonText);
			this.checkCountTaskService.saveCountData(jsonArray,taskCode);
			return "true";
		} catch (Exception e) {
			
			logger.error("error",e);
			return "false";
		}
	}
	
	//保存点数数据
	@RequestMapping(value = "ajaxFinish")
	@ResponseBody
	public String ajaxFinish(ServletRequest request,HttpServletResponse response) {
		try {	
			
			String jsonText=request.getParameter("jsonText");
			String taskCode=request.getParameter("taskCode");
			JSONArray jsonArray = JSONArray.fromObject(jsonText);
			this.checkCountTaskService.finishCountData(jsonArray,taskCode);
			return "true";
		} catch (Exception e) {
			
			logger.error("error",e);
			return "false";
		}
	}
  
	
}